package vn.lumi.smarthome.ui;

import java.util.ArrayList;

import vn.lumi.smarthome.ActivityHelper;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Scene;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.widget.TextView;

public class EditSceneActivity extends AbstractSceneActivity {

	private static final int LOADER_ID=1;
	private static final String TAG = "EditSceneActivity";
	
	@Override
	protected void onCreate(Bundle arg0) {
		//Doan nay can dat truoc super.onCreate();
		Intent intent=getIntent();
		mFloorID=intent.getIntExtra(EXTRA_FLOOR_ID, -1);
		mRoomID=intent.getIntExtra(EXTRA_ROOM_ID, -1);
		mSceneID = intent.getIntExtra(EXTRA_SCENE_ID, -1);
		oldSceneName = intent.getStringExtra(EXTRA_SCENE_NAME);
		oldSceneMode = intent.getIntExtra(EXTRA_SCENE_MODE, Scene.SCENE_MODE_NORMAL);
		mOldHour = intent.getIntExtra(EXTRA_SCENE_HOUR, 0);
		mOldMinute = intent.getIntExtra(EXTRA_SCENE_MINUTE, 0);
		mCurrentHour = mOldHour;
		mCurrentMinute = mOldMinute;
				Log.d("EditSceneActivity","edit scene floorID="+mFloorID+" room_id="+mRoomID+" sceneID="+mSceneID+" sceneName="+oldSceneName);
		
		super.onCreate(arg0);

		ActivityHelper.initialize(this);
	}
	
	@Override
	public void startLoadDeviceList(LoaderCallbacks<Device[]> loaderCallback) {
		Bundle bundle=new Bundle();
		bundle.putInt(AbstractSceneActivity.EXTRA_TYPE, TYPE_EDIT);
//		bundle.putInt(AbstractSceneActivity.EXTRA_FLOOR_ID, mFloorID);
//		bundle.putInt(AbstractSceneActivity.EXTRA_ROOM_ID, mRoomID);
		getSupportLoaderManager().initLoader(LOADER_ID, bundle, loaderCallback).forceLoad();
	}

	@Override
	public void saveScene() {
		// TODO Auto-generated method stub
		boolean isNameChanged = (!this.oldSceneName.equals(this.medtName.getText().toString()));
		Log.d("EditScene","name changed="+isNameChanged);
		
		//mode changed?
		boolean isModeChanged = false;
		int currentSceneMode = 0;
		if(this.tgbSchedule.isChecked()) currentSceneMode = Scene.SCENE_MODE_AUTO;
		else currentSceneMode = Scene.SCENE_MODE_NORMAL;
		if(this.oldSceneMode == currentSceneMode
				&& this.mOldHour == this.mCurrentHour
				&& this.mOldMinute == this.mCurrentMinute)
			isModeChanged = false;
		else
			isModeChanged = true;
		Log.d("EditScene", "mode changed=" +isModeChanged);
		
		//separate devices
		boolean isDevicesChanged = false;
		this.mNewDevices = this.mDeviceListAdapter.getDevices();
		ArrayList<Integer> unchangedNormalDevicesID = new ArrayList<Integer>();
		ArrayList<Integer> unchangedNormalDevicesState = new ArrayList<Integer>();
		ArrayList<Integer> unchangedRGBsID = new ArrayList<Integer>();
		ArrayList<Integer> unchangedRGBsState = new ArrayList<Integer>();
		ArrayList<Integer> changedNormalDevicesID = new ArrayList<Integer>();
		ArrayList<Integer> changedNormalDevicesState = new ArrayList<Integer>();
		ArrayList<Integer> changedRGBsID = new ArrayList<Integer>();
		ArrayList<Integer> changedRGBsState = new ArrayList<Integer>();
		ArrayList<Integer> newNormalDevicesID = new ArrayList<Integer>();
		ArrayList<Integer> newNormalDevicesState = new ArrayList<Integer>();
		ArrayList<Integer> newRGBsID = new ArrayList<Integer>();
		ArrayList<Integer> newRGBsState = new ArrayList<Integer>();
		ArrayList<Integer> deletedNormalDevicesID = new ArrayList<Integer>();
		ArrayList<Integer> deletedRGBsID = new ArrayList<Integer>();
		
		for(int i=0; i<mNewDevices.length;i++){
			if(mNewDevices[i].isSelected() == true && mOldDevices[i].isSelected() == true){
				if(!mNewDevices[i].getDeviceState().equals(mOldDevices[i].getDeviceState())){
					//changed device
					if(mNewDevices[i].getType_id() == Device.DEVICE_TYPE_RGB){
						changedRGBsID.add(mNewDevices[i].getId());
						changedRGBsState.add(mNewDevices[i].getDeviceState().getRGB());
					}
					else{
						changedNormalDevicesID.add(mNewDevices[i].getId());
						changedNormalDevicesState.add(mNewDevices[i].getDeviceState().getValue());
					}
				}
				else{
					//unchanged device
					if(mNewDevices[i].getType_id() == Device.DEVICE_TYPE_RGB){
						unchangedRGBsID.add(mNewDevices[i].getId());
						unchangedRGBsState.add(mNewDevices[i].getDeviceState().getRGB());
					}
					else{
						unchangedNormalDevicesID.add(mNewDevices[i].getId());
						unchangedNormalDevicesState.add(mNewDevices[i].getDeviceState().getValue());
					}
				}
			}
			else if(mNewDevices[i].isSelected()==true && mOldDevices[i].isSelected() == false){
				//new device
				if(mNewDevices[i].getType_id() == Device.DEVICE_TYPE_RGB){
					newRGBsID.add(mNewDevices[i].getId());
					newRGBsState.add(mNewDevices[i].getDeviceState().getRGB());
				}
				else{
					newNormalDevicesID.add(mNewDevices[i].getId());
					newNormalDevicesState.add(mNewDevices[i].getDeviceState().getValue());
				}
			}
			else if(mNewDevices[i].isSelected() == false && mOldDevices[i].isSelected() == true){
				//deleted device
				if(mNewDevices[i].getType_id() == Device.DEVICE_TYPE_RGB){
					deletedRGBsID.add(mNewDevices[i].getId());
				}
				else{
					deletedNormalDevicesID.add(mNewDevices[i].getId());
				}
			}
		}
		if(changedNormalDevicesID.size() == 0
				&& changedRGBsID.size() == 0
				&& newNormalDevicesID.size() ==0
				&& newRGBsID.size() == 0
				&& deletedNormalDevicesID.size() == 0
				&& deletedRGBsID.size() == 0)
			isDevicesChanged = false;
		else
			isDevicesChanged = true;
		
		Log.d("EditScene","devices changed="+isDevicesChanged);
		Log.d("EditScene","changed devices:"+changedNormalDevicesID.toString()+" changed RGBs:"+changedRGBsID.toString()+ " new devices:"+newNormalDevicesID.toString()+" new RGBs:"+newRGBsID.toString()+ " deleted devices:"+deletedNormalDevicesID.toString()+" deleted RGBs:"+deletedRGBsID.toString());
		
		//if nothing changed
		if(isNameChanged==false && isDevicesChanged == false && isModeChanged == false) finish();
		
		//if just name changed
		if(isNameChanged == true && isDevicesChanged == false && isModeChanged == false){
			ContentValues values = new ContentValues();
			values.put(TBL_Scene.NAME, this.medtName.getText().toString());
			String selection = new String(TBL_Scene._ID+"=?");
			String[] selectionArgs = new String[]{this.mSceneID+""};
			this.getApplication().getContentResolver().update(TBL_Scene.CONTENT_URI_SCENE, values, selection, selectionArgs);
			finish();
		}
		
		else if(isDevicesChanged == true||isModeChanged == true){
			ContentValues values = new ContentValues();
			values.put("Scene name", this.medtName.getText().toString());
			values.put("Scene ID", this.mSceneID);
			values.put("Room id", this.mRoomID);
			values.put("Scene mode", currentSceneMode);
			values.put("Hour", mCurrentHour);
			values.put("Minute", mCurrentMinute);
			
			values.put("unchangedNormalDevicesID", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray(unchangedNormalDevicesID)));;
			values.put("unchangedNormalDevicesState", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray(unchangedNormalDevicesState)));
			
			values.put("unchangedRGBsID", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray(unchangedRGBsID)));
			values.put("unchangedRGBsState", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray( unchangedRGBsState)));
			
			values.put("changedNormalDevicesID", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray(changedNormalDevicesID)));;
			values.put("changedNormalDevicesState", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray(changedNormalDevicesState)));
			
			values.put("changedRGBsID", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray(changedRGBsID)));
			values.put("changedRGBsState", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray( changedRGBsState)));
			
			values.put("newNormalDevicesID", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray(newNormalDevicesID)));;
			values.put("newNormalDevicesState", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray( newNormalDevicesState)));
			
			values.put("newRGBsID", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray( newRGBsID)));
			values.put("newRGBsState", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray( newRGBsState)));
			
			values.put("deletedNormalDevicesID", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray( deletedNormalDevicesID)));
			values.put("deletedRGBsID", AbstractSceneActivity.convertIntArrayToString(convertArrayListToArray( deletedRGBsID)));
			
			this.getApplicationContext().getContentResolver().update(TBL_Scene.CONTENT_URI_EDIT_SCENE, values, null, null);
			Log.d(TAG, "Sending command to CP");
			
			//show dialog
			dialog = new ProgressDialog(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
			dialog.setMessage(getString(R.string.txt_saving_scene_in_HC));
		    dialog.setCancelable(false);
		    dialog.show();
		    // Thay doi font chu cua Dialog
			ChangeFont changeFont = new ChangeFont(
					this);
			TextView textView = (TextView) dialog
					.findViewById(android.R.id.message);
			textView = changeFont.changeFontTextView(textView,
					R.string.txt_saving_scene_in_HC, LumiHome.font, 16,
					Gravity.NO_GRAVITY, getResources().getColor(R.color.greenActionbar));
		    
		    //set broadcast receiver
		    EditSceneReceiver mEditSceneReceiver = new EditSceneReceiver(dialog);
		    IntentFilter filter= new IntentFilter();
		    filter.addAction(getString(R.string.txt_vn_lumi_smarthome_edit_scene_successful));
		    filter.addAction(getString(R.string.txt_vn_lumi_smarthome_edit_scene_failed));
		    this.registerReceiver(mEditSceneReceiver, filter);
		    Log.d(TAG,"Registered broadcast receiver");
		}
	}
	
	public int[] convertArrayListToArray(ArrayList<Integer> input){
		int[] result = new int[input.size()];
		for(int i=0;i<input.size();i++){
			result[i] = input.get(i);
		}
		return result;
	}
	
	public class EditSceneReceiver extends BroadcastReceiver {
		
		private ProgressDialog mDialog;
		public EditSceneReceiver(ProgressDialog dialog){
			mDialog = dialog;
		}
	   @Override
	   public void onReceive(Context context, Intent intent) {
		   mDialog.cancel();
		   unregisterReceiver(this);
		   if( intent.getAction().equals(context.getString(R.string.txt_vn_lumi_smarthome_edit_scene_successful))){
			   Log.d(TAG, "received success");
			   finish();
		   }
		   else if(intent.getAction().equals(context.getString(R.string.txt_vn_lumi_smarthome_edit_scene_failed))){
			   Log.d(TAG, "received failed");
			   showCustomDialog(R.string.txt_error, R.string.txt_error_cannot_connect_HC);
		   }
	   }

	}
}

